package cn.edu.bupt.blog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 拦截所有controller抛出的异常
 */
@ControllerAdvice
public class ControllerExceptionHandle {
    // 获取日志日志对象
    private final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandle.class);

    /**
     * 异常处理
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public ModelAndView handleException(HttpServletRequest request,Exception e) throws Exception {
        // 日志输出 {} ： 占位符
        logger.error("Request URL : {} , Exception : {}",request.getRequestURL(),e.getClass());

        // 当代码错误引发的异常类与注解标记的类一直，则抛出异常
        if(AnnotationUtils.findAnnotation(this.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("url",request.getRequestURL());
        mav.addObject("excepation",e);
        // 跳转到对应页面
        mav.setViewName("error/error");
        return mav;
    }
}
